package task

import (
	"aicloud/monitor-apiserver/pkg/metric"
	"aicloud/monitor-apiserver/server/response"
	"fmt"
)

func GetTotalUserTrend(request metric.TrendRequest) (*response.UserTotalTrendResponse, error) {
	var (
		resp = &response.UserTotalTrendResponse{Series: response.TimeSeriesResponse{}}
	)

	totalUser, err := getTotalUser()
	if err != nil {
		return nil, err
	}
	query := `user_count_total`
	res, err := metric.QueryRange(query, request)
	if err != nil {
		return nil, err
	}
	resp.Total = int(totalUser)
	resp.Series.Series = metric.GetSeries([]metric.SeriesRequest{{Label: "totalUsers", Samples: res[0].Values}})
	return resp, nil
}

func GetOrderTrend(idcName string, request metric.TrendRequest) (*response.OrderTotalTrendResponse, error) {

	var (
		orderTotalQuery, orderAmountQuery string
		resp                              = &response.OrderTotalTrendResponse{Series: response.TimeSeriesResponse{}}
	)

	if idcName == "" {
		orderTotalQuery = `sum(order_total_count)`
		orderAmountQuery = `sum(order_total_amount)`

	} else {
		orderTotalQuery = fmt.Sprintf(`order_total_count{data_center="%s"}`, idcName)
		orderAmountQuery = fmt.Sprintf(`order_total_amount{data_center="%s"}`, idcName)
	}

	amountRes, err := metric.Query(orderAmountQuery)
	if err != nil {
		return nil, err
	}
	orderCurRes, err := metric.Query(orderTotalQuery)
	if err != nil {
		return nil, err
	}
	orderRes, err := metric.QueryRange(orderTotalQuery, request)
	if err != nil {
		return nil, err
	}
	resp.Total = int(orderCurRes[0].Value)
	resp.TotalOrderAmount = float64(amountRes[0].Value)
	resp.Series.Series = metric.GetSeries([]metric.SeriesRequest{{Label: "totalUsers", Samples: orderRes[0].Values}})
	return resp, nil
}

func GetGpuRentedTrend(idcName string, request metric.TrendRequest) (*response.GpuRentedTrendResponse, error) {

	var (
		rentedRateQuery, idleGpuRateQuery string
		resp                              = &response.GpuRentedTrendResponse{Series: response.TimeSeriesResponse{}}
	)
	if idcName == "" {
		idleGpuRateQuery = `rate(sum(idle_gpu_count))[5m]`
		rentedRateQuery = `rate(sum(gpu_rental_count))[5m]`
	} else {
		idleGpuRateQuery = fmt.Sprintf(`rate(idle_gpu_count{data_center="%s"})[5m]`, idcName)
		rentedRateQuery = fmt.Sprintf(`rate(gpu_rental_count{data_center="%s"})[5m]`, idcName)
	}
	rentedRes, err := metric.QueryRange(rentedRateQuery, request)
	if err != nil {
		return nil, err
	}
	idleRes, err := metric.QueryRange(idleGpuRateQuery, request)
	if err != nil {
		return nil, err
	}
	resp.Series.Series = metric.GetSeries([]metric.SeriesRequest{
		{Label: "rentedCards", Samples: rentedRes[0].Values},
		{Label: "idlePowerRate", Samples: idleRes[0].Values}})
	return resp, nil
}
